package atguigu.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;

/**
 * 动态代理技术，代理业务层的接口实现类
 * 添加事务管理
 */
@Component
public class ProxyFactory {
    @Autowired
    private ConnectionManager connectionManager;
    /**
     * 定义方法，传递业务层的接口实现类
     * 返回该实现类的代理对象
     */
    public Object getInstance(Object obj){
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
                obj.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = null;
                        try {
                            connectionManager.begin();
                            //调用业务层的接口实现类的方法，转账方法transfer
                            //result接收transfer方法的返回值
                            result = method.invoke(obj,args);
                            connectionManager.commit();
                        } catch (Exception e) {
                            e.printStackTrace();
                            connectionManager.rollback();
                        }
                        return result;
                    }
                });
    }
}
